package com.fun._多线程RPC;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * @author liyiruo
 * @Description
 * @Date 2021/3/22 下午1:49
 */
public class MyService implements Runnable {

    final static Integer cap = 100000;
    static volatile Integer index = 0;
    volatile static ArrayList<Integer> list = new ArrayList(cap);

    //从数据库查出需要的数据
    static {
        for (int i = 0; i < cap; i++) {
            list.add(i, i);
        }
    }


    @Override
    public void run() {
        Integer integer = getNext();
        long id = Thread.currentThread().getId();
        String name = Thread.currentThread().getName();
        System.out.println("integer=>" + integer + "id=>" + id + "name=>" + name);
    }

    public static synchronized Integer getNext() {
        if (index < cap - 1) {
            index++;
        } else {
            return -1;
        }
        return list.get(index);
    }


    //线程池执行方法
    public static void exRun(Runnable runnable) {
        ExecutorService fixedThreadPool = newFixedThreadPool(12);
        //使用for循环创建线程，其实最终 只使用了一个线程。
        for (int i = 0; i < 50; i++) {
            fixedThreadPool.execute(runnable);
        }
        //fixedThreadPool.execute(runnable);
        fixedThreadPool.shutdown();
    }

    public static void main(String[] args) {
        for (int i = 0; i < cap; i++) {
            exRun(new MyService());
        }

    }
}
